<template>
  <div class="sort">
    <n-space align="center">
      <div
        v-for="(item, index) in value"
        :key="index"
        :class="['sort__item', { active: item.value === order }]"
        @click="handleClick(item.value)"
      >
        <div class="name">{{ item.label }}</div>
        <n-icon size="16">
          <SortDescendingOutlined v-if="item.value === order && sort === 'desc'" />
          <SortAscendingOutlined v-else />
        </n-icon>
      </div>
    </n-space>
  </div>
</template>

<script setup lang="ts">
  import { NSpace, NIcon } from 'naive-ui'
  import { SortAscendingOutlined, SortDescendingOutlined } from '@vicons/antd'
  import { nextTick, ref } from 'vue'

  const props = defineProps({
    value: {
      type: Array,
      default: () => []
    },
    order: {
      type: String,
      default: ''
    },
    sort: {
      type: String,
      default: null
    }
  })
  const emits = defineEmits(['update:sort', 'update:order', 'update'])
  const sortMap = {
    asc: 'desc',
    desc: null
  }

  function onSort() {
    if (!props.sort) {
      emits('update:sort', 'asc')
    } else {
      emits('update:sort', sortMap[props.sort])
    }
  }

  async function handleClick(value: string) {
    if (value === props.order) {
      onSort()
    } else {
      await emits('update:sort', null)
      onSort()
      emits('update:order', value)
    }

    nextTick(() => {
      if (!props.sort) {
        emits('update:order', '')
      }
    })

    emits('update')
  }
</script>

<style scoped lang="scss">
  @import '@/assets/styles/var.scss';
  .sort {
    &__item {
      display: flex;
      align-items: center;
      cursor: pointer;
      padding: 3px 10px;
      border-radius: 2px;
      border: 1px solid rgb(224, 224, 230);
      transition: all 0.3s;
      user-select: none;
      &.active {
        background: $primaryColor;
        color: #ffffff;
        border: 1px solid $primaryColor;
        transition: all 0.4s;
      }
    }
  }
</style>
